//
//  TKMainViewController.swift
//  TKWBOne
//
//  Created by tiankun on 16/8/22.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import SVProgressHUD

class TKMainViewController: UITabBarController {
    
    private var timer:Timer?
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildViewControllers()
        setupComposeButton()
        setupTimer()
        delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: TKUserShouldLoginNotification), object: nil)
    }

    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    //通知监听方法
    @objc private func userLogin(n: Notification) {
        print("用户登录通知\(n)")
        var when = DispatchTime.now()
        //token过期 需要重新登录
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已超时,需要重新登录")
            //修改延迟时间
            when = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: TKOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
        
    }
    
    private lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    @objc private func composeBtnClick() {
        print("composeBtnClick")
        let vc = TKTestViewController()
        let nav = UINavigationController(rootViewController:vc)
        present(nav, animated: true, completion: nil)
    }

}
//MARK: 时钟相关方法
extension TKMainViewController {
    private func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    //时钟触发方法
    @objc private func updateTimer() {
        if !TKNetworkManager.shared.userLogon {
            return
        }
        TKNetworkManager.shared.unreadCount { (count) in
            print("监测到\(count)条新微博")
            //设置首页tabBarItem的badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            //设置APP的badgeNumber,iOS8之后需要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}
extension TKMainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //获取将要跳转到的控制器的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        //判断当前是在首页 并且index也是首页
        if selectedIndex == 0 && index == selectedIndex {
            //让表格滚动到顶部
            //获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! TKHomeViewController
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64) , animated: true)
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
        }
      
        //判断viewController是否是UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}


extension TKMainViewController {
    private func setupChildViewControllers() {
        //获取沙盒json地址
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]
            else {
                return
        }
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controllerFromDict(dict: dict))
        }
        viewControllers = arrayM
        
    }
    
    private func setupComposeButton() {
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        tabBar.addSubview(composeButton)
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
    }
    
    private func controllerFromDict(dict:[String : AnyObject]) ->UIViewController {
        //取出字典内容
        guard let clsName = dict["clsName"] as? String,
            title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
            cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? TKBaseViewController.Type,
            visitorInfo = dict["visitorInfo"] as? [String:String]
        
            else {
                return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDict = visitorInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12)], for: .normal)
        let nav = TKNavigationController(rootViewController: vc)
        return nav
    }

}
